package xyz.csmcool.imserver.mqHander;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import xyz.csmcool.imserver.config.HttpAuthHandler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 什锦
 * @Package xyz.csmcool.imchat.service.impl
 * @since 2022/8/14 0:39
 */

@Component
public class RabbitReceiver {


    private static final long RETRY_INTERVAL = 2;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "roomchat", durable = "true", arguments = {
            @Argument(name = "x-dead-letter-exchange", value = "deadExchange")
    }),
            exchange = @Exchange(value = "broadcast1", durable = "true", type = "fanout",
                    ignoreDeclarationExceptions = "true"), key = "im.roomchat"))
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception {
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        boolean success = false;
        try {
            //手工ACK
            MessageHeaders headers = message.getHeaders();
            Integer roomId = (Integer) headers.get("roomId");
            HttpAuthHandler.onMessage(message.getPayload().toString(), roomId);
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (success) {
            channel.basicAck(deliveryTag, false);
        } else {
            channel.basicNack(deliveryTag, false, false);
        }
    }
}
